using System;
using System.Collections.Generic;
using System.Text;

namespace PicAFlick.Domain
{
    /// <summary>
    /// Represents a directory on the physical disk
    /// </summary>
    public class DiskFolder : Folder
    {
        private string _physicalPath;

        public string PhysicalPath
        {
            get { return _physicalPath; }
            set { _physicalPath = value; }
        }

        /// <summary>
        /// Import a folder from disk
        /// <param name="path">the path to import from</param>
        /// </summary>
        public static Folder ImportFolder(string path)
        {
            Folder retVal = null;
            if (System.IO.Directory.Exists(path))
            {
                System.IO.DirectoryInfo d = new System.IO.DirectoryInfo(path);
                retVal = ImportFolder(d);
            }
            else
            {
                throw new System.IO.DirectoryNotFoundException(string.Format("The supplied Path was not found({1})", path));
            }
            return retVal;
        }

        public static Folder ImportFolder(System.IO.DirectoryInfo dir)
        {
            DiskFolder retVal = new DiskFolder();
            retVal.Name = dir.Name;
            retVal.PhysicalPath = dir.FullName;

            foreach (System.IO.DirectoryInfo subDir in dir.GetDirectories())
            {
                DiskFolder subFolder = (DiskFolder)DiskFolder.ImportFolder(subDir);
                if (subFolder.Images.Count > 0 || subFolder.SubFolders.Count > 0)
                {

                    retVal.SubFolders.Add(subFolder);
                    subFolder.ParentFolder = retVal;
                }

            }
            retVal.Populate();
            return retVal;

        }

        protected override void Populate()
        {
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(this.PhysicalPath);
            foreach (System.IO.FileInfo fi in dir.GetFiles("*.jpg"))
            {
                ImageDetails id = ImageDetails.ImportImage(fi);
                if (id != null)
                {
                    id.PrimaryFolder = this;
                    this.Images.Add(id);
                   //  id.MakeThumbnail();
                }


            }
            foreach (Folder f in this.SubFolders)
            {
                if (f is DiskFolder)
                {
                   // ((DiskFolder)f).Populate();
                }
            }
            this.SortImageByFileSize();
        }
        public override System.IO.Stream GetImageStream(string p)
        {
            string filename = System.IO.Path.Combine(this.PhysicalPath, p);
            System.IO.Stream retVal = System.IO.File.Open(filename, System.IO.FileMode.Open,System.IO.FileAccess.Read,System.IO.FileShare.Read);
            return retVal;

        }

    }
}
